/*
 * jUploadTemplate.js
 * name:xiaojia 小嘉
 * email:iatt@qq.com
 * qq:273142650
 * time:2012.6.1 11:00 今天六一~
*/

$(document).ready(

	function () {
		
		jUploadTemplate.data.debug = false;

		jUploadTemplate.init();

		$.jPhotoAlbum.data.template = $.jStyle.load('jPhotoAlbum');

		$(window).resize(

			function () {

				jUploadTemplate.modelMain();

			}

		);

	}

);

var jUploadTemplate = {

	init: function () {

		this.tip.load();

		this.getConfig();

		this.data.loading = $('.loading');

		this.data.ul = $('.file_list ul');

		this.frame.id = this.get('id');

		this.ieA();

		this.modelMain();

		this.loadFile();

	},

	getConfig: function () {

		var _this = this;

		$.ajax({

			type: 'GET',

			url: 'config.xml',

			dataType: 'xml',

			cache: !this.data.debug,

			async: false,

			success: function (xmlHttp) {

				_this.data.config = $(xmlHttp).find('config');

			}

		});

	},

	ieA: function () {

		$('a').bind('focus',

			function () {
	
				this.blur();
	
			}
	
		);

	},

	get: function (name) {

		url = location.href;

		url = url.replace(/(\s|\S)[^\?]*\#/ig, '').split('&');

		for (i = 0; i < url.length; i++) {

			jQueryleft = url[i].replace(/[=](\s|\S)*/ig, '');

			if (jQueryleft == name) {

				return url[i].replace(/(\s|\S)*[^=]*=/ig, '');

			}

		}

		return null;

	},

	tip: {

		load: function () {

			if (!this.cookie()) {

				var masks = $('<div class="tip_masks"></div>').appendTo(document.body);

				masks.css('opacity', 0.35);

				var tip = $('<div class="tip"><div class="close-1"></div><div class="close-2"></div></div>').appendTo(document.body);

				tip.css({

					top: $(window).height() / 2 - 210,

					left: $(window).width() / 2 - 230

				});

				tip.find('.close-1,.close-2').bind('click',

				function () {

					masks.remove();

					tip.remove();

				}

			);

			}

		},

		inArray: function (array, string) {

			for (var i = 0; i < array.length; i++) {

				if (array[i] == string) {

					return i;

				}

			}

			return -1;

		},

		cookie: function () {

			var cookie = document.cookie.split(';');

			if (this.inArray(cookie, 'jUploadTemplateTip=0') == -1) {

				document.cookie = 'jUploadTemplateTip=0';

				return false;

			} else {

				return true;

			}

		}

	},

	data: {

		jUploadTemplateFileList: null,

		folderList: null,

		error: null,

		debug: true,

		fileList: null,

		ul: null,

		loading: null,

		nowObj: $(),

		rightData: null,

		config: null,

		gradient: {

			menu: 150,

			loadFile: 100,

			getJlayer: 500

		}

	},

	frame: {

		id: null

	},

	state: {

		parent: 0,

		nowFolderInfo: null,

		nowFileInfo: null,

		parentTextArr: [],

		parentIndexArr: []

	},

	loadFile: function () {

		var _this = this;

		$.ajax({

			type: 'GET',

			url: this.data.config.find('server add[key=getLoadList]').attr('value') + '?folderID=' + this.state.parent,

			dataType: 'xml',

			cache: false,

			beforeSend: function () {

				_this.data.loading.fadeIn(_this.data.gradient.loadFile);

			},

			success: function (xmlHttp) {

				_this.data.jUploadTemplateFileList = $(xmlHttp).find('jUploadTemplateFileList');

				_this.data.folderList = $(xmlHttp).find('jUploadTemplateFileList folder');

				_this.data.fileList = $(xmlHttp).find('jUploadTemplateFileList file');

				_this.data.error = $(xmlHttp).find('jUploadTemplateFileList error');

				_this.createMenu();

				_this.createList();

			}

		});

	},

	createList: function () {

		var _this = this;

		var ul = this.data.ul;

		var folder = this.data.folderList;

		var file = this.data.fileList;

		var error = this.data.error;

		var obj, fileInfo, dom;

		this.data.loading.fadeOut(_this.data.gradient.loadFile);

		ul.html('');

		if (error.find('add').size() > 0) {

			top.$.jLayer.alert({

				subject: error.find('add:[key=explain]').attr('value')

			});

		}

		folder.find('add').each(

			function () {

				obj = $(this);

				fileInfo = obj.attr('type') + '\n大小：' + _this.B2MB(obj.attr('size')) + ' MB\n最后更新：' + obj.attr('updateTime') + '\n创建时间：' + obj.attr('createTime');

				dom = $('<li title="' + fileInfo + '" class="folder"><div class="masks"></div><div class="ico folder"><img class="' + obj.index() + '" src="' + obj.attr('ico') + '" /></div><div class="tit">' + obj.attr('name') + '</div></li>').appendTo(ul);

				_this.drawImage(dom.find('img'), obj.attr('width'), obj.attr('height'), 100, 100);

			}

		);

		file.find('add').each(

			function () {

				obj = $(this);

				fileInfo = obj.attr('type') + '\n大小：' + _this.B2MB(obj.attr('size')) + 'MB\n尺寸：' + obj.attr('width') + ' × ' + obj.attr('height') + ' \n创建时间：' + obj.attr('createTime');

				dom = $('<li title="' + fileInfo + '" class="file"><div class="masks"></div><div class="ico"><img class="' + obj.index() + '"  src="' + obj.attr('ico') + '" /></div><div class="tit">' + obj.attr('name') + '</div></li>').appendTo(ul);

				_this.drawImage(dom.find('img'), obj.attr('width'), obj.attr('height'), 100, 100);

			}

		);

		this.allEvents();

	},

	drawImage: function (dom, width, height, fitWidth, fitHeight) {

		if (width > 0 && height > 0) {

			if (width / height >= fitWidth / fitHeight) {

				if (width > fitWidth) {

					$(dom).css('width', fitWidth + 'px');

					$(dom).css('height', (height * fitWidth) / width + 'px');

				} else {

					$(dom).css('width', width + 'px');

					$(dom).css('height', height + 'px');

				}

			} else {

				if (height > fitHeight) {

					$(dom).css('height', fitHeight + 'px');

					$(dom).css('width', (width * fitHeight) / height + 'px');

				} else {

					$(dom).css('width', width + 'px');

					$(dom).css('height', height + 'px');

				}

			}

		}

	},

	createMenu: function () {

		var text = this.state.parentTextArr;

		var index = this.state.parentIndexArr;

		var ul = $('.list_title_t ul');

		ul.html('');

		for (var i = 0; i < index.length; i++) {

			ul.append('<li><a href="javascript:;" class="' + index[i] + '">' + text[i] + '</a></li>');

		}

		this.Event.navigation();

	},

	B2MB: function (size) {

		return this.ForDight(size / 1024 / 1024, 2);

	},

	hrefHash: function (parent) {

		location.hash = 'parent=' + parent;

	},

	ForDight: function (Dight, How) {

		Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);

		return Dight;

	},

	modelMain: function () {

		$.browser.msie ? jQueryscroll = 0 : jQueryscroll = 0;

		margin = $(document.body).width() * 0.05 - jQueryscroll;

		margin > 40 ? margin = 40 : '';

		margin < 20 ? margin = 20 : '';

		bWidth = parseInt($(document.body).width() - margin);

		$('#model_main').css('width', bWidth + 'px');

	},

	allEvents: function () {

		this.Event.init();

	},

	close: function (id) {

		parent.$.jLayer.close('#' + id);

	},

	fileOpen: function (file, id) {

		parent.$.jUpload.data.url = file.attr('url');

		parent.$.jUpload.data.thum = file.attr('ico');

		parent.$.jUpload.bind();

		this.close(id);

	},

	menu: {

		par: function () {

			return jUploadTemplate;

		},

		back: function (i) {

			var text = this.par().state.parentTextArr;

			var index = this.par().state.parentIndexArr

			if (text.length <= i) {

				this.root();

			} else {

				var li = $('.list_title_t ul li');

				$('.list_title_t ul li').eq(li.size() - 1 - i).find('a').click();

			}

		},

		root: function () {

			this.par().state.parent = 0;

			this.par().state.parentTextArr = [];

			this.par().state.parentIndexArr = [];

			this.par().state.nowFileInfo = null;

			this.par().loadFile();

		},

		open: function (type) {

			var par = this.par();

			var _this = this;

			switch (type) {

				case 'folder':

					var folder = par.state.nowFolderInfo;

					par.state.parent = folder.attr('index');

					par.state.parentTextArr.push(folder.attr('name'));

					par.state.parentIndexArr.push(par.state.parent);

					par.loadFile();

				break;

				case 'file':

					var dom;

					var file = par.state.nowFileInfo;

					var id = par.frame.id;

					if (id != null) {

						if (file.attr('number') > 1) {

							_this.getJlayer({

								id: 'jUploadTemplateFileSizeList_' + id,

								title: '文件列表',

								src: par.data.config.find('model add:[key=fileSizeList]').attr('value') + '?array=' + file.attr('array') + '&id=' + id,

								width: '500px',

								height: 'auto',

								margin: '80px auto'

							});

						} else {

							par.fileOpen(file, id);

						}

					} else {

						this.slides('file');

					}

				break;
			}

		},

		slides: function (type) {

			var par = this.par();

			switch (type) {

				case 'folder':

					var folder = par.state.nowFolderInfo;

					$.jPhotoAlbum.load(par.data.config.find('server add:[key=getSlidesList]').attr('value') + '?folderID=' + folder.attr('index'));

				break;

				case 'file':

					var file = par.state.nowFileInfo;

					$.jPhotoAlbum.load(par.data.config.find('server add:[key=getSlidesList]').attr('value') + '?folderID=' + par.state.parent + '&defaultID=' + file.attr('index'));

				break;

				case 'document':

					$.jPhotoAlbum.load(par.data.config.find('server add:[key=getSlidesList]').attr('value') + '?folderID=' + par.state.parent);

				break;

			}

		},

		Delete: function (type) {

			var par = this.par();

			var _this = this;

			switch (type) {

				case 'folder':

					var folder = par.state.nowFolderInfo;

					top.$.jLayer.confirm({

						title: '确认提示',

						subject: '确认删除文件夹"' + folder.attr('name') + '"和其目录下的所有文件吗？',

						sure: function () {

							_this.deleteAjax('id=' + folder.attr('index') + '&type=folder');

						}

					});

				break;

				case 'file':

					var file = par.state.nowFileInfo;

					top.$.jLayer.confirm({

						title: '确认提示',

						subject: '确认删除"' + file.attr('name') + '"吗？',

						sure: function () {

							_this.deleteAjax('id=' + file.attr('index') + '&type=file');

						}

					});

				break;

			}

		},

		deleteAjax: function (data) {

			var par = this.par();

			var _this = this;

			$.ajax({

				type: 'GET',

				url: par.data.config.find('server add:[key=deleteFolder]').attr('value'),

				data: data,

				success: function (xmlHttp) {

					if (xmlHttp == "0") {

						top.$.jLayer.alert('登录超时');

					} else {

						_this.refresh();

					}

				}

			});

		},

		refresh: function () {

			this.back(0);

		},

		attr: function (type) {

			var par = this.par();

			var id = '';

			switch (type) {

				case 'folder':

					id = par.state.nowFolderInfo.attr('index');

					break;
				case 'file':

					id = par.state.nowFileInfo.attr('index');

					break;
				case 'parent':

					id = par.state.parent;

					if (id == 0) {

						top.$.jLayer.alert({

							subject: '不可以查看根目录属性',

							background: '#fff'

						});

						return;

					}

					break;

			}

			this.getJlayer({

				id: 'jUploadTemplateSwfUploadLayer_' + id,

				title: '文件属性',

				src: par.data.config.find('model add:[key=fileAttr]').attr('value') + '?type=' + type + '&id=' + id,

				width: '500px',

				height: 'auto',

				margin: '80px auto'

			});

		},

		New: function () {

			var par = this.par();

			this.getJlayer({

				id: 'jUploadTemplateNewFolderLayer',

				title: '新建文件夹',

				src: par.data.config.find('model add:[key=newFolder]').attr('value'),

				width: '350px',

				height: '100px',

				only: 1,

				opacity: 0.35,

				background: '#fff',

				ready: function () {

					$('#newFolderInput').focus();

				}

			});

		},

		upload: function () {

			var par = this.par();

			this.getJlayer({

				id: 'jUploadTemplateSwfUploadLayer',

				title: '文件上传',

				src: par.data.config.find('model add:[key=upload]').attr('value'),

				width: '460px',

				height: 'auto',

				margin: '80px auto',

				only: 1,

				opacity: 0.35,

				background: '#fff'

			});

		},

		getJlayer: function (json) {

			var _this = this;

			var par = this.par();

			var box = top.$.jLayer.layer({

				id: json.id,

				title: json.title,

				margin: json.margin,

				width: json.width,

				height: json.height,

				only: json.only,

				opacity: json.opacity,

				background: json.background,

				subject: '<img src="style/images/loading.gif"/>',

				size: 0

			});

			if (typeof box != 'undefined') {

				var iframe = $('<div style="display:none;"></div>').appendTo(box.find('.jqe-ui-jLayer-layer-body'));

				$.ajax({

					type: 'GET',

					url: json.src,

					cache: !par.data.debug,

					success: function (xmlHttp) {

						box.find('.jqe-ui-jLayer-layer-body').find('img:eq(0)').fadeOut(par.data.gradient.getJlayer,

							function () {
	
								$(this).remove();
	
								iframe.html(xmlHttp).fadeIn(par.data.gradient.getJlayer, function () {
	
									if (typeof json.ready == 'function') {
	
										json.ready();
	
									}
	
								});
	
							}
	
						);

					}

				});

			}

		}

	},

	fileOper: {

		list: function (type) {

			var par = jUploadTemplate;

			var _this = this;

			var right = par.data.rightData.find('li');

			right.find('a:[class=open]').bind('click',

				function () {
	
					par.menu.open(type);
	
				}
	
			);

			right.find('a:[class=slides]').bind('click',

				function () {
	
					par.menu.slides(type);
	
				}
	
			);

			right.find('a:[class=rename]').bind('click',
	
				function () {
	
					par.menu.attr(type);
	
				}
	
			);

			right.find('a:[class=delete]').bind('click',
	
				function () {
	
					par.menu.Delete(type);
	
				}
	
			);

			right.find('a:[class=attr]').bind('click',

				function () {
	
					par.menu.attr(type);
	
				}
	
			);

		},

		document: function () {

			var par = jUploadTemplate;

			var _this = this;

			var right = par.data.rightData.find('li');

			right.find('a:[class=upload]').bind('click',

				function () {
	
					par.menu.upload();
	
				}
	
			);

			right.find('a:[class=slides]').bind('click',
	
				function () {
	
					par.menu.slides('document');
	
				}
	
			);

			right.find('a:[class=new]').bind('click',
	
				function () {
	
					par.menu.New();
	
				}
	
			);

			right.find('a:[class=attr]').bind('click',

				function () {
	
					par.menu.attr('parent');
	
				}
	
			);

			right.find('a:[class=back]').bind('click',

				function () {
	
					par.menu.back(1);
	
				}
	
			);

			right.find('a:[class=root]').bind('click',

				function () {
	
					par.menu.root();
	
				}
	
			);

			right.find('a:[class=refresh]').bind('click',
	
				function () {
	
					par.menu.refresh();
	
				}
	
			);

		}

	},

	Event: {

		init: function () {

			this.listMouseEvents();

			this.documentMouseEvent();

		},

		par: function () {

			return jUploadTemplate;

		},

		createNowFolderInfo: function (index) {

			this.par().state.nowFolderInfo = this.par().data.folderList.find('add:eq(' + index + ')');

		},

		createNowFileInfo: function (index) {

			this.par().state.nowFileInfo = this.par().data.fileList.find('add:eq(' + index + ')');

		},

		navigation: function () {

			var par = this.par();

			var ul = $('.list_title_t ul');

			ul.find('a').click(

				function () {
		
					var index = $(this).parent().index() + 1;
		
					par.state.parent = $(this).attr('class'),
		
					par.state.nowFileInfo = null;
		
					par.state.parentTextArr.splice(index, par.state.parentTextArr.length),
		
					par.state.parentIndexArr.splice(index, par.state.parentIndexArr.length),
		
					par.loadFile();
		
				}
		
			);

		},

		removeRightData: function () {

			if (this.par().data.rightData != null) {

				this.par().data.rightData.remove();

			}

		},

		listMouseEvents: function () {

			var par = this.par();

			var _this = this;

			var ul = this.par().data.ul;

			var event = ul.find('li .masks');

			event.bind('click',
	
				function () {
	
					par.data.nowObj.removeClass('hover');
	
					$(this).parent().addClass('hover');
	
					par.data.nowObj = $(this).parent();
	
				}
	
			);

			event.bind('dblclick',

				function () {
	
					var li = $(this).parent();
	
					var index = li.find('img').attr('class');
	
					if (li.hasClass('folder')) {
	
						_this.createNowFolderInfo(index);
	
						par.menu.open('folder');
	
					} else {
	
						_this.createNowFileInfo(index);
	
						par.menu.open('file');
	
					}
	
				}
	
			);

			event.bind('contextmenu',

				function (e) {
		
					var html, event, type;
		
					var li = $(this).parent();
		
					var index = li.find('img').attr('class');
		
					$(this).click();
		
					html = '<li><a href="javascript:;" onfocus="this.blur()" class="open">打开</a></li><li><a href="javascript:;" onfocus="this.blur()" class="slides">幻灯片浏览</a></li><li class="space"><a href="javascript:;" onfocus="this.blur()" class="rename">重命名</a></li><li><a href="javascript:;" onfocus="this.blur()" class="delete">删除</a></li><li class="space"><a href="javascript:;" onfocus="this.blur()" class="attr">属性</a></li>';
		
					if (li.hasClass('folder')) {
		
						event = par.fileOper.list;
		
						type = 'folder';
		
						_this.createNowFolderInfo(index);
		
					} else {
		
						event = par.fileOper.list;
		
						type = 'file';
		
						_this.createNowFileInfo(index);
		
					}
		
					_this.menu(e, html, event, type);
		
				}
		
			);

		},

		documentMouseEvent: function () {

			var par = this.par();

			var _this = this;

			$(document).bind('click',

				function (e) {
	
					var target = $(e.target);
	
					if (target.is('[class!=masks]')) {
	
						par.data.nowObj.removeClass('hover');
	
					}
	
					_this.removeRightData();
	
				}
	
			);

			$(document).bind('contextmenu',

				function () {
	
					return false;
	
				}
	
			);

			$(document).bind('contextmenu',

				function (e) {
		
					var target = $(e.target);
		
					if (target.is('[class!=masks]')) {
		
						html = '<li><a href="javascript:;" onfocus="this.blur()" class="back">返回上一级</a></li><li><a href="javascript:; onfocus="this.blur()" class="root">返回根目录</a></li><li class="space"><a href="javascript:;" onfocus="this.blur()" class="slides">幻灯片浏览</a></li><li class="space"><a href="javascript:;" onfocus="this.blur()" class="new">新建文件夹</a></li><li><a href="javascript:;" onfocus="this.blur()" class="upload">上传文件</a></li><li class="space"><a href="javascript:;" onfocus="this.blur()" class="refresh">刷新</a></li><li><a href="javascript:;" onfocus="this.blur()" class="attr">属性</a></li>';
		
						_this.menu(e, html, par.fileOper.document);
		
						par.data.nowObj.removeClass('hover');
		
					}
		
				}
		
			);

		},

		menu: function (e, html, event, type) {

			var par = this.par();

			var wWidth = $(window).width();

			var wHeight = $(window).height();

			var t = e.pageY;

			var l = e.pageX;

			this.removeRightData();

			par.data.rightData = $('<div class="contextmenu" style="display:none;"><ul>' + html + '</ul></div>').appendTo(document.body);

			par.data.rightData.fadeIn(par.data.gradient.menu);

			if (par.data.rightData.width() + 2 > wWidth - l) {

				l -= par.data.rightData.width();

			}

			if (par.data.rightData.height() + 2 > wHeight - t) {

				t -= par.data.rightData.height();

			}

			par.data.rightData.css({

				top: t + 'px',

				left: l + 'px'

			});

			event(type);

		}

	}

}

var fileAttr = {

	serverConfig: function (key) {

		return jUploadTemplate.data.config.find('server add[key=' + key + ']').attr('value');

	},

	updateFileName: function (obj) {

		var obj = $(obj);

		var input = obj.find('.search input:eq(0)');

		var button = obj.find('button:[type=submit]');

		var val = input.val();

		var id = obj.find('.fileID').val();

		var type = obj.find('.filedType').val();

		if (val.length <= 0) {

			top.$.jLayer.alert({

				subject: '文件夹名不允许为空！',

				background: '#fff'

			});

			return false;

		}

		if (val.search(/[!@#jQuery%^&*?;'\\\/]/ig) != -1) {

			top.$.jLayer.alert({

				subject: '不允许输出特殊字符(! @ # jQuery % ^ & * ? ; \\ / \')',

				background: '#fff'

			});

			return false;

		}

		$.ajax({

			type: 'POST',

			url: this.serverConfig('setUploadAttr'),

			data: 'name=' + escape(val) + '&id=' + id + '&type=' + type,

			beforeSend: function () {

				input.attr('disabled', true);

			},

			success: function (xmlHttp) {

				input.attr('disabled', false);

				jUploadTemplate.menu.refresh();

				top.$.jLayer.alert({

					title: '提示',

					background: '#fff',

					subject: '文件名“' + val + '”修改成功'

				});

			}

		});

		return false;

	},

	paging_search: function (obj) {

		var obj = $(obj);

		var but = obj.parent().find('button');

		if (obj.val().length > 0) {

			but.fadeIn(300);

		} else {

			but.fadeOut(300);

		}

	}

}